<template>
  <div class="route-planning">
    <div class="route-header">
      <h1 class="page-title">路线规划</h1>
      <div class="route-actions">
        <el-button @click="goBack">返回</el-button>
        <el-button v-if="!isReadonly" type="primary" @click="saveRoutes">保存路线</el-button>
      </div>
    </div>

    <div class="route-form-container">
      <el-form :model="routeForm" :rules="rules" ref="routeFormRef" label-width="100px">
        <el-form-item label="路线标题" prop="title" :rules="rules.title">
          <el-input v-model="routeForm.title" placeholder="请输入路线标题" :disabled="isReadonly"></el-input>
        </el-form-item>
        
        <el-form-item label="关联旅行计划">
          <el-select v-model="routeForm.planId" placeholder="请选择关联旅行计划" filterable clearable @change="onPlanChange" :disabled="isReadonly">
            <el-option v-for="plan in planOptions" :key="plan.id" :label="plan.title" :value="plan.id" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="关联每日计划">
          <el-select v-model="routeForm.dailyPlanId" placeholder="请选择关联每日计划" filterable clearable :disabled="isReadonly || !routeForm.planId">
            <el-option v-for="dp in dailyPlanOptions" :key="dp.id" :label="formatDailyPlanLabel(dp)" :value="dp.id" />
          </el-select>
        </el-form-item>
        
        <div class="route-items">
          <div v-for="(route, index) in routeForm.routes" :key="index" class="route-item">
            <div class="route-item-header">
              <h3>路线 {{ index + 1 }}</h3>
              <el-button 
                v-if="!isReadonly && routeForm.routes.length > 1" 
                type="danger" 
                size="small" 
                circle 
                @click="removeRoute(index)" 
                icon="Delete">
              </el-button>
            </div>

            <el-form-item label="出发地" :prop="`routes[${index}].origin`" :rules="rules.origin">
              <el-autocomplete
                v-model="route.origin"
                :fetch-suggestions="(q, cb)=>fetchOriginSuggestions(index, q, cb)"
                placeholder="请输入出发地（支持关键字）"
                @select="(item)=>onOriginSelect(index, item)"
                :disabled="isReadonly"
              />
            </el-form-item>

            <el-form-item label="目的地" :prop="`routes[${index}].destination`" :rules="rules.destination">
              <el-autocomplete
                v-model="route.destination"
                :fetch-suggestions="(q, cb)=>fetchDestinationSuggestions(index, q, cb)"
                placeholder="请输入目的地（支持关键字）"
                @select="(item)=>onDestinationSelect(index, item)"
                :disabled="isReadonly"
              />
            </el-form-item>

            <div class="form-row">
              <el-form-item label="交通方式" :prop="`routes[${index}].transportType`" :rules="rules.transportType">
                <el-select v-model="route.transportType" placeholder="请选择交通方式" :disabled="isReadonly">
                  <el-option label="步行" value="walking"></el-option>
                  <el-option label="公交" value="transit"></el-option>
                  <el-option label="驾车" value="driving"></el-option>
                  <el-option label="骑行" value="riding"></el-option>
                  <el-option label="飞机" value="flying"></el-option>
                  <el-option label="火车" value="train"></el-option>
                  <el-option label="其他" value="other"></el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="预计用时">
                <div class="eta-and-policy">
                  <el-tag type="success">{{ route.etaText || '暂未获取' }}</el-tag>
                  <template v-if="route.transportType === 'driving'">
                    <el-select class="policy-select" v-model="route.drivingPolicy" placeholder="驾车策略" :disabled="isReadonly">
                      <el-option label="最快" value="least_time" />
                      <el-option label="最经济" value="least_fee" />
                      <el-option label="最短" value="least_distance" />
                      <el-option label="避开拥堵" value="avoid_congestion" />
                    </el-select>
                  </template>
                  <template v-else-if="route.transportType === 'transit'">
                    <el-select class="policy-select" v-model="route.transitPolicy" placeholder="公交策略" :disabled="isReadonly">
                      <el-option label="耗时最短" value="least_time" />
                      <el-option label="换乘最少" value="less_transfer" />
                      <el-option label="步行最少" value="less_walk" />
                    </el-select>
                  </template>
                </div>
              </el-form-item>
            </div>

            <el-form-item label="备注">
              <el-input v-model="route.note" type="textarea" :rows="2" placeholder="添加路线备注信息" :disabled="isReadonly"></el-input>
            </el-form-item>

            <div class="map-container">
              <div :id="`map-${index}`" class="map-box"></div>
              <div class="map-actions">
                <el-button type="primary" @click="previewRoute(route, index)">预览路线</el-button>
              </div>
              <div class="route-stats" v-if="route.etaText || route.distanceText">
                <el-descriptions :column="3" size="small">
                  <el-descriptions-item label="预计用时">{{ route.etaText || '-' }}</el-descriptions-item>
                  <el-descriptions-item label="总距离">{{ route.distanceText || '-' }}</el-descriptions-item>
                  <el-descriptions-item v-if="route.stats && route.stats.cost != null" label="预计费用">{{ route.stats.cost }} 元</el-descriptions-item>
                </el-descriptions>
              </div>
            </div>
          </div>
        </div>

        <div class="add-route-action" v-if="!isReadonly">
          <el-button type="primary" plain icon="Plus" @click="addRoute">添加路线</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { authUtils } from '../../utils/auth'
import { createRoute, updateRoute, getRouteById, getRoutesByPlanId } from '../../api/route'
import { getTravelPlans, getTravelPlanById } from '../../api/travelPlan'

const route = useRoute()
const router = useRouter()
const routeFormRef = ref(null)
// 统一为数字以匹配 el-select 的 option 值（避免显示 ID 文本）
const planId = route.query.planId ? Number(route.query.planId) : ''
const dailyPlanId = route.query.dailyPlanId ? Number(route.query.dailyPlanId) : ''
const routeId = route.query.routeId || null
const originQuery = route.query.origin || ''
const destinationQuery = route.query.destination || ''
const pointsQuery = route.query.points || ''

// 只读模式：当路由参数 readonly 为真时启用
const isReadonly = computed(() => {
  const v = route.query.readonly
  if (v === undefined || v === null) return false
  return v === '1' || v === 1 || v === true || v === 'true'
})

// 高德地图 JSAPI v2 集成配置
const AMAP_KEY = 'c3ea87d6c59607d6879ebfbe1ac1b973'
const AMAP_SECURITY = 'efdc950db73cf46818881d663511bbc9'
const mapInstances = ref({})
const routeServices = ref({})
let geocoder = null

// 旅行计划与每日计划选项
const planOptions = ref([])
const dailyPlanOptions = ref([])
// 当前计划关联的城市名称（用于搜索优先）
const planCityName = ref('')

const loadAMap = () => {
  return new Promise((resolve, reject) => {
    if (window.AMap) {
      if (!geocoder) {
        window.AMap.plugin('AMap.Geocoder', () => {
          geocoder = new window.AMap.Geocoder()
          resolve()
        })
      } else {
        resolve()
      }
      return
    }
    window._AMapSecurityConfig = { securityJsCode: AMAP_SECURITY }
    const script = document.createElement('script')
    script.src = `https://webapi.amap.com/maps?v=2.0&key=${AMAP_KEY}&plugin=AMap.Driving,AMap.Walking,AMap.Transfer,AMap.Riding,AMap.Geocoder,AMap.AutoComplete,AMap.PlaceSearch`
    script.onload = () => {
      window.AMap.plugin('AMap.Geocoder', () => {
        geocoder = new window.AMap.Geocoder()
        resolve()
      })
    }
    script.onerror = () => reject(new Error('AMap脚本加载失败'))
    document.head.appendChild(script)
  })
}

const createMapIfNotExists = (index) => {
  if (mapInstances.value[index]) {
    return mapInstances.value[index]
  }
  const map = new window.AMap.Map(`map-${index}`, {
    resizeEnable: true,
    zoom: 12
  })
  mapInstances.value[index] = map
  return map
}

const clearRouteRender = (index) => {
  try {
    const svc = routeServices.value[index]
    if (svc) {
      if (typeof svc.clear === 'function') svc.clear()
      if (typeof svc.setMap === 'function') svc.setMap(null)
    }
  } catch (_) {}
  const map = mapInstances.value[index]
  if (map && typeof map.clearMap === 'function') map.clearMap()
}

const getRouteService = (index, mode, map, city, opts = {}) => {
  let svc = routeServices.value[index]
  const DrivingPolicyMap = {
    least_time: window.AMap?.DrivingPolicy?.LEAST_TIME,
    least_fee: window.AMap?.DrivingPolicy?.LEAST_FEE,
    least_distance: window.AMap?.DrivingPolicy?.LEAST_DISTANCE,
    avoid_congestion: window.AMap?.DrivingPolicy?.AVOID_CONGESTION
  }
  const TransferPolicyMap = {
    least_time: window.AMap?.TransferPolicy?.LEAST_TIME,
    less_transfer: window.AMap?.TransferPolicy?.LESS_TRANSFER,
    less_walk: window.AMap?.TransferPolicy?.LESS_WALK
  }
  const createSvc = () => {
    let s
    if (mode === 'walking') {
      s = new window.AMap.Walking({ map })
    } else if (mode === 'transit') {
      const policy = TransferPolicyMap[opts.transitPolicy || 'least_time']
      s = new window.AMap.Transfer({ map, city: city || '全国', policy })
    } else if (mode === 'riding') {
      s = new window.AMap.Riding({ map })
    } else {
      const policy = DrivingPolicyMap[opts.drivingPolicy || 'least_time']
      s = new window.AMap.Driving({ map, policy })
    }
    s.__mode = mode
    s.__policy = JSON.stringify(opts || {})
    routeServices.value[index] = s
    return s
  }

  if (!svc || svc.__mode !== mode || (svc.__policy || '{}') !== JSON.stringify(opts || {})) {
    clearRouteRender(index)
    svc = createSvc()
  } else {
    if (typeof svc.setMap === 'function') svc.setMap(map)
    if (typeof svc.clear === 'function') svc.clear()
  }
  return svc
}

const geocode = (address) => {
  return geocodeInCity(address, '全国')
}

const geocodeInCity = (address, city) => {
  return new Promise((resolve, reject) => {
    if (!address) return reject(new Error('地址为空'))
    window.AMap.plugin('AMap.Geocoder', () => {
      const localGeocoder = new window.AMap.Geocoder({ city: city || '全国' })
      localGeocoder.getLocation(address, (status, result) => {
        if (status === 'complete' && result.geocodes && result.geocodes.length) {
          resolve(result.geocodes[0].location)
        } else {
          reject(new Error('地址解析失败'))
        }
      })
    })
  })
}

const poiSearchRef = ref(null)
// 根据目标城市获取/更新 PlaceSearch 实例
const ensurePoiSearch = (city) => new Promise((resolve) => {
  window.AMap.plugin('AMap.PlaceSearch', () => {
    const targetCity = city || '全国'
    if (!poiSearchRef.value) {
      poiSearchRef.value = new window.AMap.PlaceSearch({ city: targetCity, citylimit: targetCity !== '全国' })
      poiSearchRef.value.__city = targetCity
    } else {
      if (poiSearchRef.value.__city !== targetCity) {
        if (typeof poiSearchRef.value.setCity === 'function') {
          poiSearchRef.value.setCity(targetCity)
        }
        if (typeof poiSearchRef.value.setCityLimit === 'function') {
          poiSearchRef.value.setCityLimit(targetCity !== '全国')
        }
        poiSearchRef.value.__city = targetCity
      }
    }
    resolve(poiSearchRef.value)
  })
})

// 在指定城市范围内获取自动完成建议
const fetchSuggestionsInCity = async (query, cb, city) => {
  try {
    if (!query) { cb([]); return }
    await loadAMap()
    window.AMap.plugin('AMap.AutoComplete', () => {
      const ac = new window.AMap.AutoComplete({ city: city || '全国', citylimit: (city || '全国') !== '全国' })
      ac.search(query, (status, result) => {
        if (status === 'complete' && result.tips) {
          const list = result.tips
            .filter(t => t.name)
            .map(t => ({ value: t.name, tip: t }))
          cb(list)
        } else {
          cb([])
        }
      })
    })
  } catch (_) {
    cb([])
  }
}

// 兼容旧调用（默认全国）
const fetchSuggestions = async (query, cb) => fetchSuggestionsInCity(query, cb, '全国')

// 按优先城市解析名称为POI
const resolvePoiByName = async (name) => {
  const ps = await ensurePoiSearch(getPreferredCity())
  return new Promise((resolve) => {
    ps.search(name, (status, result) => {
      if (status === 'complete' && result?.poiList?.pois?.length) {
        const poi = result.poiList.pois[0]
        resolve({ name: poi.name, location: poi.location, cityname: poi.cityname })
      } else {
        geocodeInCity(name, getPreferredCity()).then(loc => resolve({ name, location: loc, cityname: getPreferredCity() }))
      }
    })
  })
}

// —— 旅行计划与每日计划：选项加载与联动 ——
const formatDailyPlanLabel = (dp) => {
  if (!dp) return ''
  const dayText = dp.day ? `第${dp.day}天` : `ID ${dp.id}`
  return dp.date ? `${dayText} (${dp.date})` : dayText
}

const loadPlanOptions = async () => {
  try {
    const currentUserId = authUtils.getCurrentUser()?.id
    const plans = await getTravelPlans(currentUserId ? { userId: currentUserId } : {})
    const list = Array.isArray(plans) ? plans : []
    planOptions.value = list.map(p => ({ id: p.id, title: p.title }))
  } catch (e) {
    console.error('获取旅行计划列表失败:', e)
  }
}

const loadDailyPlans = async (pid) => {
  try {
    dailyPlanOptions.value = []
    if (!pid) return
    const plan = await getTravelPlanById(pid)
    // 保存计划城市名称，用于搜索优先
    planCityName.value = plan?.cityName || ''
    const dps = Array.isArray(plan?.dailyPlans) ? plan.dailyPlans : []
    dailyPlanOptions.value = dps.map(dp => ({ id: dp.id, day: dp.day, date: dp.date, cityName: dp.cityName || planCityName.value }))
  } catch (e) {
    console.error('获取每日计划失败:', e)
  }
}

const onPlanChange = async (pid) => {
  if (isReadonly.value) { ElMessage.warning('只读模式不支持修改'); return }
  routeForm.dailyPlanId = ''
  await loadDailyPlans(pid)
}

const onOriginSelect = async (idx, item) => {
  if (isReadonly.value) { return }
  const poi = await resolvePoiByName(item.value)
  routeForm.routes[idx].origin = poi.name
  routeForm.routes[idx].originPoi = poi
  routeFormRef.value?.validateField(`routes[${idx}].origin`)
}

const onDestinationSelect = async (idx, item) => {
  if (isReadonly.value) { return }
  const poi = await resolvePoiByName(item.value)
  routeForm.routes[idx].destination = poi.name
  routeForm.routes[idx].destinationPoi = poi
  routeFormRef.value?.validateField(`routes[${idx}].destination`)
}

// 计算当前优先城市：每日计划城市 > 旅行计划城市 > 全国
const getPreferredCity = () => {
  const dp = dailyPlanOptions.value.find(d => d.id === routeForm.dailyPlanId)
  return (dp?.cityName || planCityName.value || '全国')
}

const fetchOriginSuggestions = (idx, query, cb) => fetchSuggestionsInCity(query, cb, getPreferredCity())
const fetchDestinationSuggestions = (idx, query, cb) => fetchSuggestionsInCity(query, cb, getPreferredCity())

// 新增：格式化与统计更新
const formatDuration = (sec) => {
  if (!sec || isNaN(sec)) return ''
  const minutes = Math.round(Number(sec) / 60)
  const hours = Math.floor(minutes / 60)
  const mins = minutes % 60
  return hours ? `${hours}小时${mins}分钟` : `${mins}分钟`
}
const formatDistance = (m) => {
  if (!m || isNaN(m)) return ''
  const km = Number(m) / 1000
  return km >= 1 ? `${km.toFixed(1)}公里` : `${Math.round(m)}米`
}
const updateRouteStats = (idx, mode, result) => {
  try {
    let duration = 0
    let distance = 0
    let cost = null
    if (mode === 'transit') {
      const plan = result?.plans?.[0]
      duration = plan?.time ?? plan?.duration ?? 0
      distance = plan?.distance ?? 0
      cost = plan?.price ?? null
    } else {
      const r = result?.routes?.[0]
      duration = r?.time ?? 0
      distance = r?.distance ?? 0
      cost = (r?.tolls ?? result?.tolls ?? result?.taxi_cost ?? null)
    }
    routeForm.routes[idx].etaText = formatDuration(duration)
    routeForm.routes[idx].distanceText = formatDistance(distance)
    routeForm.routes[idx].stats = { duration, distance, cost, mode }
  } catch (_) {}
}

// 新增：城市名规范化与POI保证
const normalizeCityName = (name) => {
  if (!name || typeof name !== 'string') return ''
  return name.replace(/(市|区|县|自治州|自治区|特别行政区|地区)$/g, '')
}
const ensurePoiByName = async (name) => {
  if (!name) return null
  try {
    const poi = await resolvePoiByName(name)
    return poi
  } catch (_) {
    return { name, location: null, cityname: getPreferredCity() }
  }
}

// 路线表单数据
const routeForm = reactive({
  planId: planId || '',
  dailyPlanId: dailyPlanId || '',
  title: '',
  routes: [
    {
      origin: '',
      destination: '',
      transportType: 'driving',
      etaText: '',
      distanceText: '',
      drivingPolicy: 'least_time',
      transitPolicy: 'least_time',
      note: '',
      stats: null
    }
  ]
})

// 路线数据
const routes = ref([
  {
    origin: '',
    destination: '',
    transportType: 'driving',
    duration: 30,
    note: ''
  }
])

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入路线标题', trigger: 'blur' }
  ],
  origin: [
    { required: true, message: '请输入出发地', trigger: 'blur' }
  ],
  destination: [
    { required: true, message: '请输入目的地', trigger: 'blur' }
  ],
  transportType: [
    { required: true, message: '请选择交通方式', trigger: 'change' }
  ]
}

// 本地存储读写
const readRoutesByPlan = () => {
  try {
    const raw = localStorage.getItem('routesByPlan')
    return raw ? JSON.parse(raw) : {}
  } catch (_) {
    return {}
  }
}
const writeRoutesByPlan = (data) => {
  localStorage.setItem('routesByPlan', JSON.stringify(data))
}

// 添加路线
const addRoute = () => {
  if (isReadonly.value) { ElMessage.warning('只读模式不支持修改'); return }
  routeForm.routes.push({
    origin: '',
    destination: '',
    transportType: 'driving',
    etaText: '',
    distanceText: '',
    drivingPolicy: 'least_time',
    transitPolicy: 'least_time',
    note: '',
    stats: null
  })
}

// 删除路线
const removeRoute = (index) => {
  if (isReadonly.value) { ElMessage.warning('只读模式不支持修改'); return }
  routeForm.routes.splice(index, 1)
}

// 预览路线（集成高德地图路线规划）
const previewRoute = async (route, index) => {
  try {
    // 若为火车或飞机，直接提示不支持并不加载地图
    const modeEarly = route.transportType
    if (modeEarly === 'train' || modeEarly === 'flying') {
      ElMessage.info('该交通方式暂不支持路线规划，仅提供交通方式记录')
      // 清理已有渲染（若之前预览过），但不创建或加载地图
      clearRouteRender(index)
      routeForm.routes[index].etaText = ''
      routeForm.routes[index].distanceText = ''
      routeForm.routes[index].stats = { mode: modeEarly, unsupported: true }
      return
    }

    await loadAMap()
    const map = createMapIfNotExists(index)

    // 补齐 POI（用户未选择联想项时）并统一城市名
    const originPoi = route.originPoi || await ensurePoiByName(route.origin)
    const destPoi = route.destinationPoi || await ensurePoiByName(route.destination)
    const originCity = normalizeCityName(originPoi?.cityname)
    const destCity = normalizeCityName(destPoi?.cityname)
    const sameCity = !!originCity && !!destCity && originCity === destCity

    // 解析坐标：优先使用 POI 坐标，其次按城市进行地理编码
    const origin = originPoi?.location || await geocodeInCity(route.origin, originCity || getPreferredCity())
    const dest = destPoi?.location || await geocodeInCity(route.destination, destCity || getPreferredCity())

    // 将补齐的POI写回，便于后续同城判断与联动
    routeForm.routes[index].originPoi = originPoi
    routeForm.routes[index].destinationPoi = destPoi

    map.clearMap()

    let mode = route.transportType
    const opts = { drivingPolicy: route.drivingPolicy, transitPolicy: route.transitPolicy }

    if (mode === 'walking') {
      const walking = getRouteService(index, 'walking', map, undefined, opts)
      walking.search(origin, dest, (status, result) => {
        if (status !== 'complete') {
          ElMessage.error('步行路线规划失败')
        } else {
          updateRouteStats(index, 'walking', result)
        }
      })
    } else if (mode === 'transit') {
      // 不再强制切换为驾车：优先尝试公交，失败后再降级
      const city = (sameCity ? (originCity || destCity) : getPreferredCity()) || getPreferredCity()
      const transfer = getRouteService(index, 'transit', map, city, opts)
      transfer.search(origin, dest, (status, result) => {
        if (status !== 'complete') {
          ElMessage.warning('公交路线规划失败，已自动切换为驾车预览')
          const driving = getRouteService(index, 'driving', map, undefined, opts)
          driving.search(origin, dest, (s2, r2) => {
            if (s2 !== 'complete') {
              ElMessage.error('公交与驾车均规划失败')
            } else {
              updateRouteStats(index, 'driving', r2)
            }
          })
        } else {
          updateRouteStats(index, 'transit', result)
        }
      })
    } else if (mode === 'riding') {
      const riding = getRouteService(index, 'riding', map, undefined, opts)
      riding.search(origin, dest, (status, result) => {
        if (status !== 'complete') {
          ElMessage.error('骑行路线规划失败')
        } else {
          updateRouteStats(index, 'riding', result)
        }
      })
    } else if (mode === 'other') {
      ElMessage.info('该方式暂不支持自动规划，使用驾车预览')
      const driving = getRouteService(index, 'driving', map, undefined, opts)
      driving.search(origin, dest, (status, result) => {
        if (status !== 'complete') {
          ElMessage.error('驾车路线规划失败')
        } else {
          updateRouteStats(index, 'driving', result)
        }
      })
    } else {
      const driving = getRouteService(index, 'driving', map, undefined, opts)
      driving.search(origin, dest, (status, result) => {
        if (status !== 'complete') {
          ElMessage.error('驾车路线规划失败')
        } else {
          updateRouteStats(index, 'driving', result)
        }
      })
    }
  } catch (error) {
    console.error('路线规划失败:', error)
    ElMessage.error(error.message || '路线规划失败')
  }
}

// 保存路线到数据库
const saveRoutes = async () => {
  if (isReadonly.value) { ElMessage.warning('只读模式不支持修改'); return }
  if (!routeFormRef.value) return
  try {
    await routeFormRef.value.validate()
    
    if (!routeForm.title) {
      ElMessage.warning('请输入路线标题')
      return
    }
    
    const payload = {
      title: routeForm.title || '未命名路线',
      travelPlanId: routeForm.planId ? Number(routeForm.planId) : null,
      dailyPlanId: routeForm.dailyPlanId ? Number(routeForm.dailyPlanId) : null,
      routesData: routeForm.routes
    }
    
    let result
    if (routeId) {
      // 编辑模式：更新现有路线
      result = await updateRoute(routeId, payload)
    } else {
      // 新建模式：若同计划同日已存在路线，则改为更新以避免重复
      const targetPlanId = payload.travelPlanId
      const targetDailyPlanId = payload.dailyPlanId
      let existingSameDay = null
      try {
        if (targetPlanId && targetDailyPlanId) {
          const res = await getRoutesByPlanId(targetPlanId)
          const list = Array.isArray(res?.data) ? res.data : (Array.isArray(res) ? res : [])
          existingSameDay = list.find(r => Number(r.dailyPlanId) === Number(targetDailyPlanId)) || null
        }
      } catch (_) {}

      if (existingSameDay?.id) {
        result = await updateRoute(existingSameDay.id, payload)
      } else {
        result = await createRoute(payload)
      }
    }
    
    if (result.success) {
      ElMessage.success('路线规划保存成功')
      const targetPlanId = routeForm.planId || planId
      if (targetPlanId) {
        router.push(`/travel-plan/${targetPlanId}`)
      } else {
        router.push('/routes')
      }
    } else {
      ElMessage.error(result.message || '保存路线失败')
    }
  } catch (error) {
    console.error('保存路线失败:', error)
    ElMessage.error('保存路线失败，请检查表单')
  }
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 获取路线数据（优先加载 routeId 的后端数据；否则加载本地或查询参数）
const fetchRoutes = async () => {
  try {
    // 1) 如果是查看/编辑模式（携带 routeId），优先从后端载入并填充表单
    if (routeId) {
      const res = await getRouteById(routeId)
      const data = res?.success ? res.data : res
      if (data) {
        routeForm.title = data.title || ''
        routeForm.planId = data.travelPlanId ?? ''
        routeForm.dailyPlanId = data.dailyPlanId ?? ''
        // 统一类型为数字以匹配下拉选项
        routeForm.planId = routeForm.planId !== '' ? Number(routeForm.planId) : ''
        routeForm.dailyPlanId = routeForm.dailyPlanId !== '' ? Number(routeForm.dailyPlanId) : ''
        routeForm.routes = Array.isArray(data.routesData) ? data.routesData : (Array.isArray(data.routes) ? data.routes : routeForm.routes)
        // 若有计划，联动加载每日计划选项
        if (routeForm.planId) {
          await loadDailyPlans(routeForm.planId)
        }
        return
      }
    }

    // 2) 其次尝试读取本地已保存的当日日程路线
    const store = readRoutesByPlan()
    if (planId && dailyPlanId && store[planId] && Array.isArray(store[planId][dailyPlanId])) {
      routeForm.routes = store[planId][dailyPlanId]
      return
    }

    // 3) 最后根据查询参数进行预填（origin/destination 或 points）
    let points = []
    try {
      points = pointsQuery ? JSON.parse(decodeURIComponent(pointsQuery)) : []
    } catch (_) {
      points = []
    }
    if (points.length >= 2) {
      routeForm.routes = []
      for (let i = 0; i < points.length - 1; i++) {
        routeForm.routes.push({
          origin: points[i],
          destination: points[i + 1],
          transportType: 'driving',
          etaText: '',
          distanceText: '',
          drivingPolicy: 'least_time',
          transitPolicy: 'least_time',
          note: '',
          stats: null
        })
      }
    } else if (originQuery || destinationQuery) {
      routeForm.routes[0].origin = originQuery
      routeForm.routes[0].destination = destinationQuery
    }
  } catch (error) {
    console.error('获取路线数据失败:', error)
    ElMessage.error('获取路线数据失败')
  }
}

onMounted(async () => {
  await loadPlanOptions()
  if (routeForm.planId) {
    await loadDailyPlans(routeForm.planId)
  }
  fetchRoutes()
})
</script>

<style scoped>
.route-planning {
  padding: 20px;
  max-width: 900px;
  margin: 0 auto;
}

.route-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.page-title {
  margin: 0;
  color: #409EFF;
}

.route-form-container {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.route-items {
  margin-bottom: 20px;
}

.route-item {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 20px;
  margin-bottom: 20px;
  position: relative;
}

.route-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.route-item-header h3 {
  margin: 0;
  color: #606266;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.map-container {
  margin-top: 20px;
}

.map-box {
  height: 240px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.map-actions {
  margin-top: 10px;
}

.map-placeholder {
  height: 200px;
  background-color: #f5f7fa;
  border-radius: 4px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.add-route-action {
  text-align: center;
  margin-top: 20px;
}

.eta-and-policy {
  display: flex;
  align-items: center;
  gap: 8px;
}

.policy-select {
  width: 160px;
  margin-left: 8px;
}

.route-stats {
  margin-top: 8px;
}
</style>